import { BaseSystem } from '../base';
import { EVENTS, type IEventBus } from '../../events';
import type { PlayerStateSystem } from '../player-state';
import type { FeatureUnlockModel } from '../../model';
import { MODEL_NAME } from '../../constants/model-names';

export class FeatureUnlockSystem extends BaseSystem {
  private playerStateSystem: PlayerStateSystem;
  private bus: IEventBus;

  constructor(bus: IEventBus, playerStateSystem: PlayerStateSystem) {
    super();
    this.bus = bus;
    this.playerStateSystem = playerStateSystem;

    this.bus.on(EVENTS.REALM_STATE_UPDATE, () => {
      this.updateFeatureUnlock();
    });
    this.bus.on(EVENTS.CULTIVATION_SKILL_STATE_UPDATE, () => {
      this.updateFeatureUnlock();
    });
  }

  private updateFeatureUnlock() {
    const featureUnlockModel =
      this.playerStateSystem.getModel<FeatureUnlockModel>(
        MODEL_NAME.FEATURE_UNLOCK
      );
    featureUnlockModel?.getConditions().forEach((f) => {
      const result = this.playerStateSystem.checkConditions(f.conditions);
      if (!result) return;
      featureUnlockModel.setUnlock(f.id);
      this.bus.emit(EVENTS.FEATURE_UNLOCK_SUCCESS, f.id);
    });
  }

  public override init(): void {
    this.updateFeatureUnlock();
  }
}
